package lanbo.cj.lmp.activity;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import android.app.*;
import android.util.Log;
import lanbo.cj.lmp.Config;
import lanbo.cj.lmp.R;
import lanbo.cj.lmp.bean.Asset;
import lanbo.cj.lmp.utils.LocalData;
import lanbo.cj.lmp.view.DialogTips;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cn.bmob.v3.listener.SaveListener;

import com.google.gson.Gson;
import com.google.gson.internal.Streams;

public class WriteTagActivity extends Activity {
    private ImageView mBack;
    private EditText mName, mType, mBirth, mDate, mManu;
    private Button mSure;
    private IntentFilter[] mWriteTagFilters;
    private NfcAdapter nfcAdapter;
    PendingIntent pendingIntent;
    String[][] mTechLists;
    private boolean isWrite;
    private DatePickerDialog dateDialog, birthDialog;
    private Asset asset;
    private Map<String, Object> tagData;
    private int curAssetType;//当前资产类型
    private String[] assetItems = new String[]{"超声刀", "呼吸机",};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.write_tag);
        tagData = null;
        if (getIntent().getSerializableExtra("tagData") != null) {
            tagData = (Map<String, Object>) getIntent().getSerializableExtra("tagData");
        }
        findviewBy();
        setListener();

    }

    private void findviewBy() {
        mBack = (ImageView) findViewById(R.id.write_back);
        mName = (EditText) findViewById(R.id.write_name);
        mType = (EditText) findViewById(R.id.write_type);
        mType.setInputType(InputType.TYPE_NULL);//默认输入法不弹出
        mBirth = (EditText) findViewById(R.id.write_birth);
        mBirth.setInputType(InputType.TYPE_NULL);//默认输入法不弹出
        mDate = (EditText) findViewById(R.id.write_date);
        mDate.setInputType(InputType.TYPE_NULL);//默认输入法不弹出
        mManu = (EditText) findViewById(R.id.write_manu);
        mSure = (Button) findViewById(R.id.write_btn);

        if (tagData != null) {
            showTagData();
        }
        isWrite = false;

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, "不支持NFC", Toast.LENGTH_SHORT).show();
            finish();
            return;
        } else if (!nfcAdapter.isEnabled()) {
            Toast.makeText(this, "NFC未打开", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        // 写入标签权限
        IntentFilter writeFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        mWriteTagFilters = new IntentFilter[]{writeFilter};
        mTechLists = new String[][]{new String[]{MifareClassic.class.getName()},
                new String[]{NfcA.class.getName()}};// 允许扫描的标签类型
    }

    /**
     * 如果主界面有扫入的标签，可以在写入界面预览
     */
    private void showTagData() {
        int assetType= (int) ((double)tagData.get(Config.Tag_type));
        mName.setText((String)tagData.get(Config.Tag_name));
        mType.setText(Config.getAssetType(assetType));
        mBirth.setText((String)tagData.get(Config.Tag_birth));
        mDate.setText((String)tagData.get(Config.Tag_date));
        mManu.setText((String)tagData.get(Config.Tag_manu));
    }

    private void setListener() {
        dateDialog = new DatePickerDialog(WriteTagActivity.this, AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                //出现的莫名bug，实际月份会比显示月份少一，于是暂时先加1
                monthOfYear++;
                mDate.setText(year + "/" + monthOfYear + "/" + dayOfMonth);
            }
        }, 2015, 7, 15);
        birthDialog = new DatePickerDialog(WriteTagActivity.this, AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                monthOfYear++;
                mBirth.setText(year + "/" + monthOfYear + "/" + dayOfMonth);
            }
        }, 2015, 7, 15);
        mDate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dateDialog.show();
            }
        });
        mBirth.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                birthDialog.show();
            }
        });
        mBack.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                finish();
            }
        });

        mSure.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                final DialogTips dialog = new DialogTips(WriteTagActivity.this, "请贴近标签", "  确定写入标签", "确定", true, true);
                dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int userId) {
                        dialog.dismiss();
                        isWrite = true;
                        Toast.makeText(WriteTagActivity.this, "请在10秒中之内将手机贴近标签", Toast.LENGTH_SHORT).show();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(10000);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                finish();
                            }
                        }).start();
                    }
                });
                // 显示确认对话框
                dialog.show();
            }
        });

        //资产类型的输入改为选框输入
        mType.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mType.setText(assetItems[0]);
                AlertDialog.Builder builder = new AlertDialog.Builder(WriteTagActivity.this,android.R.style.Theme_DeviceDefault_Light_Dialog);
                builder.setTitle("选择资产类型")
                        .setSingleChoiceItems(assetItems, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                mType.setText(assetItems[i]);
                                curAssetType = i;
                            }
                        })
                        .setPositiveButton("确定",null)
                        .show();

            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, mWriteTagFilters, mTechLists);
    }

    // 写入模式时，才执行写入操作
    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        if (isWrite && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            NdefMessage ndefMessage = getNoteAsNdef();
            if (ndefMessage != null) {
                if (writeTag(getNoteAsNdef(), tag)){
                    asset.save(WriteTagActivity.this, new SaveListener() {

                        @Override
                        public void onSuccess() {
                            // TODO Auto-generated method stub
                            showToast("上传资产数据成功");
                        }

                        @Override
                        public void onFailure(int arg0, String arg1) {
                            // TODO Auto-generated method stub
                            LocalData localData = new LocalData();
                            localData.saveData(asset);
                            showToast("将数据存至本地,已缓存记录个数:"+localData.getLocalData().size()+"");
                            return;
                        }
                    });
                }
            } else {
                showToast("请输入您要写入标签的内容");
            }
        }
    }

    // 根据文本生成一个NdefRecord
    private NdefMessage getNoteAsNdef() {
        String name = mName.getText().toString().trim();
        String type = mType.getText().toString().trim();
        String birth = mBirth.getText().toString().trim();
        String date = mDate.getText().toString().trim();
        String manu = mManu.getText().toString().trim();


        Map<String, Object> map = new HashMap<String, Object>();
        map.put(Config.Tag_name, name);
        map.put(Config.Tag_type, curAssetType);
        map.put(Config.Tag_birth, birth);
        map.put(Config.Tag_date, date);
        map.put(Config.Tag_manu, manu);
        map.put(Config.Tag_state,Config.STATE_NOT_USE);
        map.put(Config.Tag_curOperation,"暂无使用过");
        map.put(Config.Tag_curKeshi,Config.Keshi_NULL);
        String tapID = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        map.put(Config.Tag_id, tapID);

        asset = new Asset();
        asset.setAssetType(type);
        asset.setManufactor(manu);
        asset.setName(name);
        asset.setCusId(tapID);
        asset.setKeShiId(0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd");
        try {
            Date fabDate = sdf.parse(birth);
            asset.setFabDate(fabDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Toast.makeText(WriteTagActivity.this, "日期书写错误", Toast.LENGTH_SHORT).show();
        }
        asset.setStatus(Config.STATE_NOT_USE);

        Gson gson = new Gson();
        String tag = gson.toJson(map);

        byte[] textBytes = tag.getBytes();
        // image/jpeg text/plain
        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "image/jpeg".getBytes(), new byte[]{},
                textBytes);
        return new NdefMessage(new NdefRecord[]{textRecord});

    }


    // 写入tag
    boolean writeTag(NdefMessage message, Tag tag) {

        int size = message.toByteArray().length;

        try {
            Ndef ndef = Ndef.get(tag);
            if (ndef != null) {
                ndef.connect();

                if (!ndef.isWritable()) {
                    showToast("tag不允许写入");
                    return false;
                }
                if (ndef.getMaxSize() < size) {
                    showToast("文件大小超出容量");
                    return false;
                }

                ndef.writeNdefMessage(message);

                showToast("写入数据成功.");
                ndef.close();
                finish();
                return true;
            } else {
                NdefFormatable format = NdefFormatable.get(tag);
                if (format != null) {
                    try {
                        format.connect();
                        format.format(message);
                        showToast("格式化tag并且写入message");
                        return true;
                    } catch (IOException e) {
                        showToast("格式化tag失败.");
                        return false;
                    }
                } else {
                    showToast("Tag不支持NDEF");
                    return false;
                }
            }
        } catch (Exception e) {
            showToast("写入数据失败");
        }

        return false;
    }

    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
}
